package edu.tces482.plms.zigbee;

import java.math.BigInteger;
import java.util.Arrays;

public class ZBReceivePacket extends ZBPacket {

	
	private static final short type = 0x90;
	private static final short baseFrameSize = 12;

	private BigInteger src64;
	private int src16;
	private short options;

	private final byte [] rfData;

	public ZBReceivePacket(final byte [] packet) {
		if (packet[0] == startDelimiter) {
			int length = ((0x000000FF & packet[1]) << 8) + (0x000000FF & packet[2]);
			if (4 + length == packet.length) {
				byte chksum = calculateChecksum(packet, 3, length);
				if (packet[packet.length - 1] == chksum) {
					src64 = new BigInteger(1, Arrays.copyOfRange(packet, 4, 12));
					src16 = (((0x000000FF & packet[12]) << 8) | (0x000000FF & packet[13]));
					options = packet[14];
					rfData = Arrays.copyOfRange(packet, 15, packet.length - 1);
				} else {
					throw new MalformedZBPacketException("Invalid checksum");
				}
			} else {
				throw new MalformedZBPacketException("Packet length did not match length field");
			}
		} else {
			throw new MalformedZBPacketException("Packet must start with 0x7E");
		}
	}
	
	@Override
	protected int getFrameSize() {
		return (baseFrameSize + rfData.length);
	}

	@Override
	protected byte[] getFrameBytes() {
		// TODO Implement getFrameBytes()
		return null;
	}

	@Override
	public int getType() { 
		return type; 
	}
	
	public BigInteger get64BitSourceAddress() {
		return src64;
	}
	
	public int get16BitSourceAddress() {
		return src16;
	}
	
	public int getOptions() {
		return options;
	}
	
	public byte [] getRfData() {
		return rfData;
	}

}
